package com.hymns.utils;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.hymns.domain.Hymn;

public class XmlHymnHandler extends DefaultHandler {
	static final String NUMBER = "number";
	static final String FILE = "file";
	static final String TITLE = "title";
	static final String TEXT = "text";
	static final String HYMN = "hymn";
	private Hymn _hymn;
	private StringBuilder _builder;

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		super.characters(ch, start, length);
		_builder.append(ch, start, length);
	}

	@Override
	public void endElement(String uri, String localName, String name)
			throws SAXException {
		super.endElement(uri, localName, name);
		if (this._hymn != null) {
			if (localName.equalsIgnoreCase(TITLE)) {
				_hymn.set_Title(_builder.toString().trim());
			} else if (localName.equalsIgnoreCase(NUMBER)) {
				_hymn.set_Number(_builder.toString().trim());
			} else if (localName.equalsIgnoreCase(TEXT)) {
				_hymn.set_Content(_builder.toString().trim());
			}
			_builder.setLength(0);
		}
	}

	@Override
	public void startDocument() throws SAXException {
		super.startDocument();
		_hymn = new Hymn();
		_builder = new StringBuilder();
	}

	@Override
	public void startElement(String uri, String localName, String name,
			Attributes attributes) throws SAXException {
		super.startElement(uri, localName, name, attributes);
		if (localName.equalsIgnoreCase(HYMN)) {

			_hymn.set_Number(attributes.getValue(NUMBER));

		}
	}

	public Hymn GetHymn() {
		return this._hymn;
	}
}
